package com.mdlib.helper.module.update;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.mdlib.helper.app.AppContext;
import com.ljlib.help.R;
import com.mdlib.helper.model.entity.UpdateInfo;
import com.mdlib.helper.utils.ToastUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


/**
 * Created by Bin on 2015/10/27.
 */
public class AppUpdate {

    private Context mContext;
    private UpdateInfo mUpdate;

    //提示语
    private String updateMsg = "有最新的软件包哦，亲快下载吧~";

    private boolean isShow = false;

    ProgressDialog mProgressDlg;

    /* 下载包安装路径 */
    private String savePath;
    private String saveFileName;

    private static final int ON_DOWNLOADING = 1;
    private static final int DOWNLOAD_FINISH = 2;
    private int progress;

    private boolean isForceUpdate;


    private Thread downLoadThread;
    private boolean interceptFlag = false;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ON_DOWNLOADING:
                    mProgressDlg.setProgress(progress + 1);
                    break;
                case DOWNLOAD_FINISH:
                    installApk();
                    break;
                default:
                    break;
            }
        }

    };


    public AppUpdate(Context context, boolean isShow, UpdateInfo updateInfo) {
        this.mContext = context;
        this.isShow = isShow;
        this.mUpdate = updateInfo;
        // 设定下载的文件路径
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            savePath = Environment.getExternalStorageDirectory() + "/" + "download";
            saveFileName = savePath + "/mdhelp.apk";
        }

    }

    public void checkUpdate() {

        if (AppContext.getInstance().getPackageInfo().versionCode < Integer.valueOf(mUpdate.getVersion())) {
        showUpdateInfo();
        }
        if (isShow) {
            ToastUtil.showToast("已经是最新版本了");
        }
    }


    private void showUpdateInfo() {
        if (mUpdate == null) {
            return;
        }

        String updateLogo = mUpdate.getDesc().replace("|", "\n");
//        final Dialog dialog = new Dialog(mContext, R.style.Dialog_Share);
        final Dialog dialog = new AlertDialog.Builder(mContext, R.style.Dialog_Share).create();
        dialog.show();
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_helper_update, null);
        dialog.setContentView(view);

        dialog.setCancelable(false);

        TextView updateContent = (TextView) dialog.findViewById(R.id.tv_content);
        updateContent.setText(updateLogo);

        ImageView updateClose = (ImageView) dialog.findViewById(R.id.iv_update_close);

        TextView confirmBtn = (TextView) dialog.findViewById(R.id.tv_update_btn);
        confirmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDownloadDialog();
                dialog.dismiss();
            }
        });

        if (mUpdate.getIs_forced() == 1) {
            updateClose.setVisibility(View.GONE);
        }


    }


    private void showDownloadDialog() {

        mProgressDlg = new ProgressDialog(mContext);
        mProgressDlg.setCancelable(false);
        mProgressDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        // 设置ProgressDialog 的进度条是否不明确 false 就是不设置为不明确
        mProgressDlg.setIndeterminate(false);
        mProgressDlg.setTitle("正在更新");
        mProgressDlg.setMessage("请稍候...");
        mProgressDlg.show();
        downloadApk();
    }


    /**
     * 下载apk
     */
    private void downloadApk() {
        downLoadThread = new Thread(mdownApkRunnable);
        downLoadThread.start();
    }

    /**
     * 安装apk
     */
    private void installApk() {
        File apkfile = new File(saveFileName);
        if (!apkfile.exists()) {
            return;
        }
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
        mContext.startActivity(i);
        ((Activity) mContext).finish();
    }

    private Runnable mdownApkRunnable = new Runnable() {
        @Override
        public void run() {
            try {

                URL url = new URL(mUpdate.getUrl());
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.connect();
                int length = conn.getContentLength();
                InputStream is = conn.getInputStream();

//                mProgressDlg.setMax((int) length);// 设置进度条的最大值

                File file = new File(savePath);
                if (!file.exists()) {
                    file.mkdir();
                }
                String apkFile = saveFileName;
                File ApkFile = new File(apkFile);
                FileOutputStream fos = new FileOutputStream(ApkFile);

                int count = 0;
                byte buf[] = new byte[1024];

                do {
                    int numread = is.read(buf);
                    count += numread;
//                    progress = count;
                    progress = (int) (((float) count / length) * 100);
                    //更新进度
                    mHandler.sendEmptyMessage(ON_DOWNLOADING);
                    if (numread <= 0) {
                        //下载完成通知安装
                        mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                        break;
                    }
                    fos.write(buf, 0, numread);
                } while (!interceptFlag);//点击取消就停止下载.

                fos.close();
                is.close();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    };


}
